#!/bin/bash

# Web Notes 服务器环境安装脚本 - Ubuntu 24.04
# 用法: ./install-dependencies-ubuntu.sh

set -e

echo "🔧 安装 Web Notes 应用依赖 (Ubuntu 24.04)..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 检查是否为 Ubuntu 24.04
check_os() {
    if [[ ! -f /etc/os-release ]] || ! grep -q "Ubuntu" /etc/os-release; then
        echo -e "${RED}此脚本仅支持 Ubuntu 系统${NC}"
        exit 1
    fi
    
    VERSION=$(grep VERSION_ID /etc/os-release | cut -d'"' -f2)
    if [[ ! $VERSION =~ ^24\. ]]; then
        echo -e "${YELLOW}警告: 此脚本针对 Ubuntu 24.04 优化，当前版本: $VERSION${NC}"
        read -p "是否继续? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
}

# 更新系统
update_system() {
    echo -e "${YELLOW}更新系统包...${NC}"
    sudo apt update
    sudo apt upgrade -y
    sudo apt install -y curl wget git vim software-properties-common htop
}

# 安装 Node.js 20
install_nodejs() {
    echo -e "${YELLOW}安装 Node.js 20...${NC}"
    
    if command -v node &> /dev/null; then
        CURRENT_VERSION=$(node --version)
        echo -e "${GREEN}Node.js 已安装: $CURRENT_VERSION${NC}"
        
        # 检查版本是否为 20.x
        if [[ $CURRENT_VERSION =~ ^v20\. ]]; then
            return
        else
            echo -e "${YELLOW}当前版本不是 Node.js 20，将升级...${NC}"
        fi
    fi
    
    # 添加 NodeSource 仓库
    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
    
    # 安装 Node.js
    sudo apt install -y nodejs
    
    echo -e "${GREEN}Node.js 安装完成: $(node --version)${NC}"
    echo -e "${GREEN}npm 版本: $(npm --version)${NC}"
}

# 安装 MongoDB 7.0
install_mongodb() {
    echo -e "${YELLOW}安装 MongoDB 7.0...${NC}"
    
    if systemctl is-active --quiet mongod; then
        echo -e "${GREEN}MongoDB 已安装并运行${NC}"
        return
    fi
    
    # 导入 MongoDB 公钥
    curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
    
    # 添加 MongoDB 仓库 (使用 jammy 兼容 24.04)
    echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
    
    # 更新包列表并安装
    sudo apt update
    sudo apt install -y mongodb-org
    
    # 启动服务
    sudo systemctl start mongod
    sudo systemctl enable mongod
    
    echo -e "${GREEN}MongoDB 安装完成${NC}"
}

# 安装 Nginx
install_nginx() {
    echo -e "${YELLOW}安装 Nginx...${NC}"
    
    if systemctl is-active --quiet nginx; then
        echo -e "${GREEN}Nginx 已安装并运行${NC}"
        return
    fi
    
    # 安装 Nginx
    sudo apt install -y nginx
    
    # 启动服务
    sudo systemctl start nginx
    sudo systemctl enable nginx
    
    echo -e "${GREEN}Nginx 安装完成${NC}"
}

# 安装 PM2
install_pm2() {
    echo -e "${YELLOW}安装 PM2...${NC}"
    
    if command -v pm2 &> /dev/null; then
        echo -e "${GREEN}PM2 已安装: $(pm2 --version)${NC}"
        return
    fi
    
    # 安装 PM2
    sudo npm install -g pm2
    
    echo -e "${GREEN}PM2 安装完成${NC}"
    echo -e "${YELLOW}请运行以下命令设置 PM2 开机自启:${NC}"
    echo -e "${YELLOW}pm2 startup${NC}"
    echo -e "${YELLOW}然后运行显示的 sudo 命令${NC}"
}

# 配置防火墙 (UFW)
configure_firewall() {
    echo -e "${YELLOW}配置防火墙 (UFW)...${NC}"
    
    # 启用 UFW
    sudo ufw --force enable
    
    # 开放端口
    sudo ufw allow 22/tcp      # SSH
    sudo ufw allow 80/tcp      # HTTP
    sudo ufw allow 443/tcp     # HTTPS
    
    echo -e "${GREEN}防火墙配置完成${NC}"
    sudo ufw status
}

# 优化系统
optimize_system() {
    echo -e "${YELLOW}优化系统配置...${NC}"
    
    # 增加文件描述符限制
    echo "* soft nofile 65535" | sudo tee -a /etc/security/limits.conf
    echo "* hard nofile 65535" | sudo tee -a /etc/security/limits.conf
    
    # 优化网络参数
    echo "net.core.somaxconn = 65535" | sudo tee -a /etc/sysctl.conf
    echo "net.ipv4.tcp_max_syn_backlog = 65535" | sudo tee -a /etc/sysctl.conf
    
    # 应用配置
    sudo sysctl -p
    
    echo -e "${GREEN}系统优化完成${NC}"
}

# 安装额外工具
install_additional_tools() {
    echo -e "${YELLOW}安装额外工具...${NC}"
    
    sudo apt install -y \
        certbot python3-certbot-nginx \
        fail2ban \
        unattended-upgrades \
        logrotate
    
    # 配置自动安全更新
    sudo dpkg-reconfigure -plow unattended-upgrades
    
    echo -e "${GREEN}额外工具安装完成${NC}"
}

# 检查安装结果
check_installation() {
    echo -e "${YELLOW}检查安装结果...${NC}"
    
    echo "Node.js: $(node --version 2>/dev/null || echo '未安装')"
    echo "npm: $(npm --version 2>/dev/null || echo '未安装')"
    echo "PM2: $(pm2 --version 2>/dev/null || echo '未安装')"
    
    echo -e "\n服务状态:"
    echo "MongoDB: $(systemctl is-active mongod 2>/dev/null || echo '未运行')"
    echo "Nginx: $(systemctl is-active nginx 2>/dev/null || echo '未运行')"
    echo "UFW: $(sudo ufw status | head -1)"
    
    echo -e "\n系统信息:"
    echo "OS: $(lsb_release -d | cut -f2)"
    echo "Kernel: $(uname -r)"
    echo "Memory: $(free -h | grep '^Mem:' | awk '{print $2}')"
    echo "Disk: $(df -h / | tail -1 | awk '{print $2}')"
}

# 显示完成信息
show_completion() {
    echo -e "\n${GREEN}🎉 Ubuntu 24.04 环境安装完成!${NC}"
    echo -e "\n${YELLOW}接下来的步骤:${NC}"
    echo -e "1. 设置 PM2 开机自启: ${YELLOW}pm2 startup${NC}"
    echo -e "2. 上传应用代码到服务器"
    echo -e "3. 运行部署脚本: ${YELLOW}./deploy-ubuntu.sh${NC}"
    
    echo -e "\n${YELLOW}有用的命令:${NC}"
    echo -e "查看服务状态: ${YELLOW}sudo systemctl status nginx mongod${NC}"
    echo -e "查看防火墙状态: ${YELLOW}sudo ufw status${NC}"
    echo -e "查看系统资源: ${YELLOW}htop${NC}"
    echo -e "查看系统日志: ${YELLOW}sudo journalctl -f${NC}"
    
    echo -e "\n${YELLOW}安全建议:${NC}"
    echo -e "1. 修改 SSH 默认端口 (可选)"
    echo -e "2. 配置 MongoDB 认证"
    echo -e "3. 设置定期备份"
    echo -e "4. 配置 SSL 证书"
}

# 主函数
main() {
    check_os
    update_system
    install_nodejs
    install_mongodb
    install_nginx
    install_pm2
    configure_firewall
    optimize_system
    install_additional_tools
    check_installation
    show_completion
}

# 运行主函数
main "$@"